<!DOCTYPE html><html lang="en"><head><link rel="stylesheet" href="./style.css"><title>Snippets Archive - 30 seconds of code</title><meta charset="utf-8"><meta name="description" content="Curated collection of useful Javascript snippets that you can understand in 30 seconds or less."><meta name="keywords" content="javascript, snippets, code, programming"><meta name="author" content="Angelos Chalaris (chalarangelo@gmail.com)"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="theme-color" content="#111"><meta property="og:title" content="30 seconds of code"><meta property="og:description" content="Curated collection of useful Javascript snippets that you can understand in 30 seconds or less."/><meta property="og:type" content="website"/><meta property="og:image" content="https://30secondsofcode.org/logos/logo_512.png"><link rel="icon" type="image/png" href="./logos/logo_128.png"><link rel="manifest" href="manifest.json"><script>const search = (node) => {
        let matchingTags = [];
        Array.from(node.parentElement.getElementsByTagName('a')).forEach(x => {
          let data = [x.textContent.toLowerCase(), ...x.getAttribute('tags').split(',')].map(v => !!(v.indexOf(node.value.toLowerCase()) + 1));
          if (data.includes(true)) {
            x.style.display = '';
            matchingTags.push(x.getAttribute('tags').split(',')[0]);
          }
          else x.style.display = 'none';
        });
        Array.from(node.parentElement.getElementsByTagName('h4')).forEach(x => {
          x.style.display = matchingTags.includes(x.textContent.toLowerCase()) ? '' : 'none';
        })
      }
      function scrollToTop() {
        const c = document.querySelector('.card-container').scrollTop;
        if (c > 0) {
          window.requestAnimationFrame(scrollToTop);
          document.querySelector('.card-container').scrollTo(0, c - c / 4);
        }
      };
      function scrollTo(element, to, id, duration) {
        if (duration <= 0) return;
        var difference = to - element.scrollTop;
        var perTick = difference / duration * 40;

        setTimeout(function () {
          element.scrollTop = element.scrollTop + perTick;
          if (element.scrollTop === to) {
            window.location.href = "#" + id;
            return;
          }
          scrollTo(element, to, id, duration - 40);
        }, 40);
      };
      function loader() {
        registerClickListener();
        if (window.innerWidth >= '768')
          document.querySelector('nav').scrollTop = Array.from(document.querySelectorAll('h4')).filter(v => v.innerHTML === '$tag')[0].offsetTop;
        else
          document.querySelector('nav').scrollTop = Array.from(document.querySelectorAll('h4')).filter(v => v.innerHTML === '$tag')[0].offsetTop;
      }
      function registerClickListener() {
        document.addEventListener('click', function (event) {
          if (event.target.classList.contains('collapse')) {
            event.target.classList = event.target.classList.contains('toggled') ? 'collapse' : 'collapse toggled';
          }
          else if (event.target.classList.contains('menu-button')) {
            document.querySelector('nav').classList = event.target.classList.contains('toggled') ? '' : 'col-nav';
            document.querySelector('[type="search"]').classList = event.target.classList.contains('toggled') ? '' : 'col-nav';
            event.target.classList = event.target.classList.contains('toggled') ? 'menu-button' : 'menu-button toggled';
          }
          else if (!document.querySelector('nav').contains(event.target) && !document.querySelector('[type="search"]').contains(event.target) && window.innerWidth < '768') {
            document.querySelector('nav').classList = '';
            document.querySelector('[type="search"]').classList = '';
            document.querySelector('.menu-button').classList = 'menu-button';
          }
          else if (event.target.classList.contains('copy-button')) {
            const text = event.target.parentElement.parentElement.querySelector(':not(pre) + pre').textContent;
            const textArea = document.createElement("textarea");
            textArea.value = text.trim();
            document.body.appendChild(textArea);
            textArea.select();
            document.execCommand("Copy");
            document.body.removeChild(textArea);
            let tst = document.createElement('div');
            tst.classList = 'toast';
            tst.innerHTML = 'Snippet copied to clipboard!';
            document.body.appendChild(tst);
            setTimeout(function () {
              tst.style.opacity = 0;
              setTimeout(function () {
                document.body.removeChild(tst);
              }, 300);
            }, 1700);
          }
        }, false);
      }</script></head><body onload="loader()" class="card-page"><a href="https://github.com/30-seconds/30-seconds-of-code" class="github-corner" aria-label="View source on Github"><svg width="56" height="56" viewBox="0 0 250 250" style="fill:#009688;color:#fff;position:fixed;top:0;border:0;right:0;z-index:1000" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin:130px 106px" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><header><h1 class="logo"><a href="./index"><img src="https://30secondsofcode.org/logos/logo_256.png" alt="logo"/><span id="title">&nbsp;30 seconds of code</span> <small>Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.</small></a></h1></header><div class="container card-container"><main class="col-centered"><span id="top"><br><br></span><h2 class="category-name">Snippets Archive</h2><p style="text-align:justify">These snippets, while useful and interesting, didn't quite make it into the repository due to either having very specific use-cases or being outdated. However we felt like they might still be useful to some readers, so here they are.</p><br/><div class="card code-card"><div class="section card-content"><h4 id="binarysearch.md">binarySearch</h4><p>Use recursion. Similar to <code>Array.prototype.indexOf()</code> that finds the index of a value within an array. The difference being this operation only works with sorted arrays which offers a major performance boost due to it's logarithmic nature when compared to a linear search or <code>Array.prototype.indexOf()</code>.</p><p>Search a sorted array by repeatedly dividing the search interval in half. Begin with an interval covering the whole array. If the value of the search is less than the item in the middle of the interval, recurse into the lower half. Otherwise recurse into the upper half. Repeatedly recurse until the value is found which is the mid or you've recursed to a point that is greater than the length which means the value doesn't exist and return <code>-1</code>.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">binarySearch</span> <span class="token operator">=</span> <span class="token punctuation">(</span>arr<span class="token punctuation">,</span> val<span class="token punctuation">,</span> start <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">,</span> end <span class="token operator">=</span> arr<span class="token punctuation">.</span>length <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span>start <span class="token operator">></span> end<span class="token punctuation">)</span> <span class="token keyword">return</span> <span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">;</span>
  <span class="token keyword">const</span> mid <span class="token operator">=</span> Math<span class="token punctuation">.</span><span class="token function">floor</span><span class="token punctuation">((</span>start <span class="token operator">+</span> end<span class="token punctuation">)</span> <span class="token operator">/</span> <span class="token number">2</span><span class="token punctuation">);</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span>arr<span class="token punctuation">[</span>mid<span class="token punctuation">]</span> <span class="token operator">></span> val<span class="token punctuation">)</span> <span class="token keyword">return</span> <span class="token function">binarySearch</span><span class="token punctuation">(</span>arr<span class="token punctuation">,</span> val<span class="token punctuation">,</span> start<span class="token punctuation">,</span> mid <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">);</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span>arr<span class="token punctuation">[</span>mid<span class="token punctuation">]</span> <span class="token operator">&lt;</span> val<span class="token punctuation">)</span> <span class="token keyword">return</span> <span class="token function">binarySearch</span><span class="token punctuation">(</span>arr<span class="token punctuation">,</span> val<span class="token punctuation">,</span> mid <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">,</span> end<span class="token punctuation">);</span>
  <span class="token keyword">return</span> mid<span class="token punctuation">;
};</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">binarySearch</span><span class="token punctuation">([</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">4</span><span class="token punctuation">,</span> <span class="token number">6</span><span class="token punctuation">,</span> <span class="token number">7</span><span class="token punctuation">,</span> <span class="token number">12</span><span class="token punctuation">,</span> <span class="token number">13</span><span class="token punctuation">,</span> <span class="token number">15</span><span class="token punctuation">,</span> <span class="token number">18</span><span class="token punctuation">,</span> <span class="token number">19</span><span class="token punctuation">,</span> <span class="token number">20</span><span class="token punctuation">,</span> <span class="token number">22</span><span class="token punctuation">,</span> <span class="token number">24</span><span class="token punctuation">],</span> <span class="token number">6</span><span class="token punctuation">);</span> <span class="token comment">// 2</span>
<span class="token function">binarySearch</span><span class="token punctuation">([</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">4</span><span class="token punctuation">,</span> <span class="token number">6</span><span class="token punctuation">,</span> <span class="token number">7</span><span class="token punctuation">,</span> <span class="token number">12</span><span class="token punctuation">,</span> <span class="token number">13</span><span class="token punctuation">,</span> <span class="token number">15</span><span class="token punctuation">,</span> <span class="token number">18</span><span class="token punctuation">,</span> <span class="token number">19</span><span class="token punctuation">,</span> <span class="token number">20</span><span class="token punctuation">,</span> <span class="token number">22</span><span class="token punctuation">,</span> <span class="token number">24</span><span class="token punctuation">],</span> <span class="token number">21</span><span class="token punctuation">);</span> <span class="token comment">// -1</span>
</pre></div><div class="card code-card"><div class="section card-content"><h4 id="cleanobj.md">cleanObj</h4><p>Removes any properties except the ones specified from a JSON object.</p><p>Use <code>Object.keys()</code> method to loop over given JSON object and deleting keys that are not included in given array. If you pass a special key,<code>childIndicator</code>, it will search deeply apply the function to inner objects, too.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">cleanObj</span> <span class="token operator">=</span> <span class="token punctuation">(</span>obj<span class="token punctuation">,</span> keysToKeep <span class="token operator">=</span> <span class="token punctuation">[],</span> childIndicator<span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
  Object<span class="token punctuation">.</span><span class="token function">keys</span><span class="token punctuation">(</span>obj<span class="token punctuation">).</span><span class="token function">forEach</span><span class="token punctuation">(</span>key <span class="token operator">=></span> <span class="token punctuation">{</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>key <span class="token operator">===</span> childIndicator<span class="token punctuation">) {</span>
      <span class="token function">cleanObj</span><span class="token punctuation">(</span>obj<span class="token punctuation">[</span>key<span class="token punctuation">],</span> keysToKeep<span class="token punctuation">,</span> childIndicator<span class="token punctuation">);
    }</span> <span class="token keyword">else if</span> <span class="token punctuation">(</span><span class="token operator">!</span>keysToKeep<span class="token punctuation">.</span><span class="token function">includes</span><span class="token punctuation">(</span>key<span class="token punctuation">)) {</span>
      <span class="token keyword">delete</span> obj<span class="token punctuation">[</span>key<span class="token punctuation">];
    }
  });</span>
  <span class="token keyword">return</span> obj<span class="token punctuation">;
};</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token keyword">const</span> testObj <span class="token operator">=</span> <span class="token punctuation">{</span> a<span class="token punctuation">:</span> <span class="token number">1</span><span class="token punctuation">,</span> b<span class="token punctuation">:</span> <span class="token number">2</span><span class="token punctuation">,</span> children<span class="token punctuation">: {</span> a<span class="token punctuation">:</span> <span class="token number">1</span><span class="token punctuation">,</span> b<span class="token punctuation">:</span> <span class="token number">2</span> <span class="token punctuation">} };</span>
<span class="token function">cleanObj</span><span class="token punctuation">(</span>testObj<span class="token punctuation">, [</span><span class="token string">'a'</span><span class="token punctuation">],</span> <span class="token string">'children'</span><span class="token punctuation">);</span> <span class="token comment">// { a: 1, children : { a: 1}}</span>
</pre></div><div class="card code-card"><div class="section card-content"><h4 id="collatz.md">collatz</h4><p>Applies the Collatz algorithm.</p><p>If <code>n</code> is even, return <code>n/2</code>. Otherwise, return <code>3n+1</code>.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">collatz</span> <span class="token operator">=</span> n <span class="token operator">=></span> <span class="token punctuation">(</span>n <span class="token operator">%</span> <span class="token number">2</span> <span class="token operator">===</span> <span class="token number">0</span> <span class="token operator">?</span> n <span class="token operator">/</span> <span class="token number">2</span> <span class="token punctuation">:</span> <span class="token number">3</span> <span class="token operator">*</span> n <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">);</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">collatz</span><span class="token punctuation">(</span><span class="token number">8</span><span class="token punctuation">);</span> <span class="token comment">// 4</span>
</pre></div><div class="card code-card"><div class="section card-content"><h4 id="countvowels.md">countVowels</h4><p>Retuns <code>number</code> of vowels in provided string.</p><p>Use a regular expression to count the number of vowels <code>(A, E, I, O, U)</code> in a <code>string</code>.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">countVowels</span> <span class="token operator">=</span> str <span class="token operator">=></span> <span class="token punctuation">(</span>str<span class="token punctuation">.</span><span class="token function">match</span><span class="token punctuation">(</span><span class="token regex">/[aeiou]/gi</span><span class="token punctuation">)</span> <span class="token operator">||</span> <span class="token punctuation">[]).</span>length<span class="token punctuation">;</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">countVowels</span><span class="token punctuation">(</span><span class="token string">'foobar'</span><span class="token punctuation">);</span> <span class="token comment">// 3</span>
<span class="token function">countVowels</span><span class="token punctuation">(</span><span class="token string">'gym'</span><span class="token punctuation">);</span> <span class="token comment">// 0</span>
</pre></div><div class="card code-card"><div class="section card-content"><h4 id="factors.md">factors</h4><p>Returns the array of factors of the given <code>num</code>. If the second argument is set to <code>true</code> returns only the prime factors of <code>num</code>. If <code>num</code> is <code>1</code> or <code>0</code> returns an empty array. If <code>num</code> is less than <code>0</code> returns all the factors of <code>-int</code> together with their additive inverses.</p><p>Use <code>Array.from()</code>, <code>Array.prototype.map()</code> and <code>Array.prototype.filter()</code> to find all the factors of <code>num</code>. If given <code>num</code> is negative, use <code>Array.prototype.reduce()</code> to add the additive inverses to the array. Return all results if <code>primes</code> is <code>false</code>, else determine and return only the prime factors using <code>isPrime</code> and <code>Array.prototype.filter()</code>. Omit the second argument, <code>primes</code>, to return prime and non-prime factors by default.</p><p><strong>Note</strong>:- <em>Negative numbers are not considered prime.</em></p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">factors</span> <span class="token operator">=</span> <span class="token punctuation">(</span>num<span class="token punctuation">,</span> primes <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
  <span class="token keyword">const</span> <span class="token function-variable function">isPrime</span> <span class="token operator">=</span> num <span class="token operator">=></span> <span class="token punctuation">{</span>
    <span class="token keyword">const</span> boundary <span class="token operator">=</span> Math<span class="token punctuation">.</span><span class="token function">floor</span><span class="token punctuation">(</span>Math<span class="token punctuation">.</span><span class="token function">sqrt</span><span class="token punctuation">(</span>num<span class="token punctuation">));</span>
    <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">var</span> i <span class="token operator">=</span> <span class="token number">2</span><span class="token punctuation">;</span> i <span class="token operator">&lt;=</span> boundary<span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token keyword">if</span> <span class="token punctuation">(</span>num <span class="token operator">%</span> i <span class="token operator">===</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token keyword">return</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> num <span class="token operator">>=</span> <span class="token number">2</span><span class="token punctuation">;
  };</span>
  <span class="token keyword">const</span> isNeg <span class="token operator">=</span> num <span class="token operator">&lt;</span> <span class="token number">0</span><span class="token punctuation">;</span>
  num <span class="token operator">=</span> isNeg <span class="token operator">? -</span>num <span class="token punctuation">:</span> num<span class="token punctuation">;</span>
  <span class="token keyword">let</span> array <span class="token operator">=</span> Array<span class="token punctuation">.</span><span class="token keyword">from</span><span class="token punctuation">({</span> length<span class="token punctuation">:</span> num <span class="token operator">-</span> <span class="token number">1</span> <span class="token punctuation">})
    .</span><span class="token function">map</span><span class="token punctuation">((</span>val<span class="token punctuation">,</span> i<span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">(</span>num <span class="token operator">%</span> <span class="token punctuation">(</span>i <span class="token operator">+</span> <span class="token number">2</span><span class="token punctuation">)</span> <span class="token operator">===</span> <span class="token number">0</span> <span class="token operator">?</span> i <span class="token operator">+</span> <span class="token number">2</span> <span class="token punctuation">:</span> <span class="token boolean">false</span><span class="token punctuation">))
    .</span><span class="token function">filter</span><span class="token punctuation">(</span>val <span class="token operator">=></span> val<span class="token punctuation">);</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span>isNeg<span class="token punctuation">)</span>
    array <span class="token operator">=</span> array<span class="token punctuation">.</span><span class="token function">reduce</span><span class="token punctuation">((</span>acc<span class="token punctuation">,</span> val<span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
      acc<span class="token punctuation">.</span><span class="token function">push</span><span class="token punctuation">(</span>val<span class="token punctuation">);</span>
      acc<span class="token punctuation">.</span><span class="token function">push</span><span class="token punctuation">(</span><span class="token operator">-</span>val<span class="token punctuation">);</span>
      <span class="token keyword">return</span> acc<span class="token punctuation">;
    }, []);</span>
  <span class="token keyword">return</span> primes <span class="token operator">?</span> array<span class="token punctuation">.</span><span class="token function">filter</span><span class="token punctuation">(</span>isPrime<span class="token punctuation">) :</span> array<span class="token punctuation">;
};</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">factors</span><span class="token punctuation">(</span><span class="token number">12</span><span class="token punctuation">);</span> <span class="token comment">// [2,3,4,6,12]</span>
<span class="token function">factors</span><span class="token punctuation">(</span><span class="token number">12</span><span class="token punctuation">,</span> <span class="token boolean">true</span><span class="token punctuation">);</span> <span class="token comment">// [2,3]</span>
<span class="token function">factors</span><span class="token punctuation">(</span><span class="token operator">-</span><span class="token number">12</span><span class="token punctuation">);</span> <span class="token comment">// [2, -2, 3, -3, 4, -4, 6, -6, 12, -12]</span>
<span class="token function">factors</span><span class="token punctuation">(</span><span class="token operator">-</span><span class="token number">12</span><span class="token punctuation">,</span> <span class="token boolean">true</span><span class="token punctuation">);</span> <span class="token comment">// [2,3]</span>
</pre></div><div class="card code-card"><div class="section card-content"><h4 id="fibonaccicountuntilnum.md">fibonacciCountUntilNum</h4><p>Returns the number of fibonnacci numbers up to <code>num</code>(<code>0</code> and <code>num</code> inclusive).</p><p>Use a mathematical formula to calculate the number of fibonacci numbers until <code>num</code>.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">fibonacciCountUntilNum</span> <span class="token operator">=</span> num <span class="token operator">=></span>
  Math<span class="token punctuation">.</span><span class="token function">ceil</span><span class="token punctuation">(</span>Math<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>num <span class="token operator">*</span> Math<span class="token punctuation">.</span><span class="token function">sqrt</span><span class="token punctuation">(</span><span class="token number">5</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token number">1</span> <span class="token operator">/</span> <span class="token number">2</span><span class="token punctuation">)</span> <span class="token operator">/</span> Math<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">((</span>Math<span class="token punctuation">.</span><span class="token function">sqrt</span><span class="token punctuation">(</span><span class="token number">5</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">)</span> <span class="token operator">/</span> <span class="token number">2</span><span class="token punctuation">));</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">fibonacciCountUntilNum</span><span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">);</span> <span class="token comment">// 7</span>
</pre></div><div class="card code-card"><div class="section card-content"><h4 id="fibonacciuntilnum.md">fibonacciUntilNum</h4><p>Generates an array, containing the Fibonacci sequence, up until the nth term.</p><p>Create an empty array of the specific length, initializing the first two values (<code>0</code> and <code>1</code>). Use <code>Array.prototype.reduce()</code> to add values into the array, using the sum of the last two values, except for the first two. Uses a mathematical formula to calculate the length of the array required.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">fibonacciUntilNum</span> <span class="token operator">=</span> num <span class="token operator">=></span> <span class="token punctuation">{</span>
  <span class="token keyword">let</span> n <span class="token operator">=</span> Math<span class="token punctuation">.</span><span class="token function">ceil</span><span class="token punctuation">(</span>Math<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>num <span class="token operator">*</span> Math<span class="token punctuation">.</span><span class="token function">sqrt</span><span class="token punctuation">(</span><span class="token number">5</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token number">1</span> <span class="token operator">/</span> <span class="token number">2</span><span class="token punctuation">)</span> <span class="token operator">/</span> Math<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">((</span>Math<span class="token punctuation">.</span><span class="token function">sqrt</span><span class="token punctuation">(</span><span class="token number">5</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">)</span> <span class="token operator">/</span> <span class="token number">2</span><span class="token punctuation">));</span>
  <span class="token keyword">return</span> Array<span class="token punctuation">.</span><span class="token keyword">from</span><span class="token punctuation">({</span> length<span class="token punctuation">:</span> n <span class="token punctuation">}).</span><span class="token function">reduce</span><span class="token punctuation">(
    (</span>acc<span class="token punctuation">,</span> val<span class="token punctuation">,</span> i<span class="token punctuation">)</span> <span class="token operator">=></span> acc<span class="token punctuation">.</span><span class="token function">concat</span><span class="token punctuation">(</span>i <span class="token operator">></span> <span class="token number">1</span> <span class="token operator">?</span> acc<span class="token punctuation">[</span>i <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">]</span> <span class="token operator">+</span> acc<span class="token punctuation">[</span>i <span class="token operator">-</span> <span class="token number">2</span><span class="token punctuation">] :</span> i<span class="token punctuation">),
    []
  );
};</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">fibonacciUntilNum</span><span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">);</span> <span class="token comment">// [ 0, 1, 1, 2, 3, 5, 8 ]</span>
</pre></div><div class="card code-card"><div class="section card-content"><h4 id="howmanytimes.md">howManyTimes</h4><p>Returns the number of times <code>num</code> can be divided by <code>divisor</code> (integer or fractional) without getting a fractional answer. Works for both negative and positive integers.</p><p>If <code>divisor</code> is <code>-1</code> or <code>1</code> return <code>Infinity</code>. If <code>divisor</code> is <code>-0</code> or <code>0</code> return <code>0</code>. Otherwise, keep dividing <code>num</code> with <code>divisor</code> and incrementing <code>i</code>, while the result is an integer. Return the number of times the loop was executed, <code>i</code>.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">howManyTimes</span> <span class="token operator">=</span> <span class="token punctuation">(</span>num<span class="token punctuation">,</span> divisor<span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span>divisor <span class="token operator">===</span> <span class="token number">1</span> <span class="token operator">||</span> divisor <span class="token operator">=== -</span><span class="token number">1</span><span class="token punctuation">)</span> <span class="token keyword">return</span> <span class="token number">Infinity</span><span class="token punctuation">;</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span>divisor <span class="token operator">===</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token keyword">return</span> <span class="token number">0</span><span class="token punctuation">;</span>
  <span class="token keyword">let</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
  <span class="token keyword">while</span> <span class="token punctuation">(</span>Number<span class="token punctuation">.</span><span class="token function">isInteger</span><span class="token punctuation">(</span>num <span class="token operator">/</span> divisor<span class="token punctuation">)) {</span>
    i<span class="token operator">++</span><span class="token punctuation">;</span>
    num <span class="token operator">=</span> num <span class="token operator">/</span> divisor<span class="token punctuation">;
  }</span>
  <span class="token keyword">return</span> i<span class="token punctuation">;
};</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">howManyTimes</span><span class="token punctuation">(</span><span class="token number">100</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">);</span> <span class="token comment">// 2</span>
<span class="token function">howManyTimes</span><span class="token punctuation">(</span><span class="token number">100</span><span class="token punctuation">,</span> <span class="token number">2.5</span><span class="token punctuation">);</span> <span class="token comment">// 2</span>
<span class="token function">howManyTimes</span><span class="token punctuation">(</span><span class="token number">100</span><span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">);</span> <span class="token comment">// 0</span>
<span class="token function">howManyTimes</span><span class="token punctuation">(</span><span class="token number">100</span><span class="token punctuation">,</span> <span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">);</span> <span class="token comment">// Infinity</span>
</pre></div><div class="card code-card"><div class="section card-content"><h4 id="httpdelete.md">httpDelete</h4><p>Makes a <code>DELETE</code> request to the passed URL.</p><p>Use <code>XMLHttpRequest</code> web api to make a <code>delete</code> request to the given <code>url</code>. Handle the <code>onload</code> event, by running the provided <code>callback</code> function. Handle the <code>onerror</code> event, by running the provided <code>err</code> function. Omit the third argument, <code>err</code> to log the request to the console's error stream by default.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">httpDelete</span> <span class="token operator">=</span> <span class="token punctuation">(</span>url<span class="token punctuation">,</span> callback<span class="token punctuation">,</span> err <span class="token operator">=</span> console<span class="token punctuation">.</span>error<span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
  <span class="token keyword">const</span> request <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">XMLHttpRequest</span><span class="token punctuation">();</span>
  request<span class="token punctuation">.</span><span class="token function">open</span><span class="token punctuation">(</span><span class="token string">'DELETE'</span><span class="token punctuation">,</span> url<span class="token punctuation">,</span> <span class="token boolean">true</span><span class="token punctuation">);</span>
  request<span class="token punctuation">.</span><span class="token function-variable function">onload</span> <span class="token operator">=</span> <span class="token punctuation">()</span> <span class="token operator">=></span> <span class="token function">callback</span><span class="token punctuation">(</span>request<span class="token punctuation">);</span>
  request<span class="token punctuation">.</span><span class="token function-variable function">onerror</span> <span class="token operator">=</span> <span class="token punctuation">()</span> <span class="token operator">=></span> <span class="token function">err</span><span class="token punctuation">(</span>request<span class="token punctuation">);</span>
  request<span class="token punctuation">.</span><span class="token function">send</span><span class="token punctuation">();
};</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">httpDelete</span><span class="token punctuation">(</span><span class="token string">'https://website.com/users/123'</span><span class="token punctuation">,</span> request <span class="token operator">=></span> <span class="token punctuation">{</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>request<span class="token punctuation">.</span>responseText<span class="token punctuation">);
});</span> <span class="token comment">// 'Deletes a user from the database'</span>
</pre></div><div class="card code-card"><div class="section card-content"><h4 id="httpput.md">httpPut</h4><p>Makes a <code>PUT</code> request to the passed URL.</p><p>Use <code>XMLHttpRequest</code> web api to make a <code>put</code> request to the given <code>url</code>. Set the value of an <code>HTTP</code> request header with <code>setRequestHeader</code> method. Handle the <code>onload</code> event, by running the provided <code>callback</code> function. Handle the <code>onerror</code> event, by running the provided <code>err</code> function. Omit the last argument, <code>err</code> to log the request to the console's error stream by default.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">httpPut</span> <span class="token operator">=</span> <span class="token punctuation">(</span>url<span class="token punctuation">,</span> data<span class="token punctuation">,</span> callback<span class="token punctuation">,</span> err <span class="token operator">=</span> console<span class="token punctuation">.</span>error<span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
  <span class="token keyword">const</span> request <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">XMLHttpRequest</span><span class="token punctuation">();</span>
  request<span class="token punctuation">.</span><span class="token function">open</span><span class="token punctuation">(</span><span class="token string">"PUT"</span><span class="token punctuation">,</span> url<span class="token punctuation">,</span> <span class="token boolean">true</span><span class="token punctuation">);</span>
  request<span class="token punctuation">.</span><span class="token function">setRequestHeader</span><span class="token punctuation">(</span><span class="token string">'Content-type'</span><span class="token punctuation">,</span><span class="token string">'application/json; charset=utf-8'</span><span class="token punctuation">);</span>
  request<span class="token punctuation">.</span><span class="token function-variable function">onload</span> <span class="token operator">=</span> <span class="token punctuation">()</span> <span class="token operator">=></span> <span class="token function">callback</span><span class="token punctuation">(</span>request<span class="token punctuation">);</span>
  request<span class="token punctuation">.</span><span class="token function-variable function">onerror</span> <span class="token operator">=</span> <span class="token punctuation">()</span> <span class="token operator">=></span> <span class="token function">err</span><span class="token punctuation">(</span>request<span class="token punctuation">);</span>
  request<span class="token punctuation">.</span><span class="token function">send</span><span class="token punctuation">(</span>data<span class="token punctuation">);
};</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token keyword">const</span> password <span class="token operator">=</span> <span class="token string">"fooBaz"</span><span class="token punctuation">;</span>
<span class="token keyword">const</span> data <span class="token operator">=</span> <span class="token constant">JSON</span><span class="token punctuation">.</span><span class="token function">stringify</span><span class="token punctuation">(</span>password<span class="token punctuation">);</span>
<span class="token function">httpPut</span><span class="token punctuation">(</span><span class="token string">'https://website.com/users/123'</span><span class="token punctuation">,</span> data<span class="token punctuation">,</span> request <span class="token operator">=></span> <span class="token punctuation">{</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>request<span class="token punctuation">.</span>responseText<span class="token punctuation">);
});</span> <span class="token comment">// 'Updates a user's password in database'</span>
</pre></div><div class="card code-card"><div class="section card-content"><h4 id="isarmstrongnumber.md">isArmstrongNumber</h4><p>Checks if the given number is an Armstrong number or not.</p><p>Convert the given number into an array of digits. Use the exponent operator (<code>**</code>) to get the appropriate power for each digit and sum them up. If the sum is equal to the number itself, return <code>true</code> otherwise <code>false</code>.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">isArmstrongNumber</span> <span class="token operator">=</span> digits <span class="token operator">=></span>
  <span class="token punctuation">(</span>arr <span class="token operator">=></span> arr<span class="token punctuation">.</span><span class="token function">reduce</span><span class="token punctuation">((</span>a<span class="token punctuation">,</span> d<span class="token punctuation">)</span> <span class="token operator">=></span> a <span class="token operator">+</span> <span class="token function">parseInt</span><span class="token punctuation">(</span>d<span class="token punctuation">)</span> <span class="token operator">**</span> arr<span class="token punctuation">.</span>length<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token operator">==</span> digits<span class="token punctuation">)(
    (</span>digits <span class="token operator">+</span> <span class="token string">''</span><span class="token punctuation">).</span><span class="token function">split</span><span class="token punctuation">(</span><span class="token string">''</span><span class="token punctuation">)
  );</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">isArmstrongNumber</span><span class="token punctuation">(</span><span class="token number">1634</span><span class="token punctuation">);</span> <span class="token comment">// true</span>
<span class="token function">isArmstrongNumber</span><span class="token punctuation">(</span><span class="token number">56</span><span class="token punctuation">);</span> <span class="token comment">// false</span>
</pre></div><div class="card code-card"><div class="section card-content"><h4 id="issimilar.md">isSimilar</h4><p>Determines if the <code>pattern</code> matches with <code>str</code>.</p><p>Use <code>String.toLowerCase()</code> to convert both strings to lowercase, then loop through <code>str</code> and determine if it contains all characters of <code>pattern</code> and in the correct order. Adapted from <a href="https://github.com/forrestthewoods/lib_fts/blob/80f3f8c52db53428247e741b9efe2cde9667050c/code/fts_fuzzy_match.js#L18">here</a>.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">isSimilar</span> <span class="token operator">=</span> <span class="token punctuation">(</span>pattern<span class="token punctuation">,</span> str<span class="token punctuation">)</span> <span class="token operator">=></span>
  <span class="token punctuation">[</span><span class="token operator">...</span>str<span class="token punctuation">].</span><span class="token function">reduce</span><span class="token punctuation">(
      (</span>matchIndex<span class="token punctuation">,</span> char<span class="token punctuation">)</span> <span class="token operator">=></span>
          char<span class="token punctuation">.</span><span class="token function">toLowerCase</span><span class="token punctuation">()</span> <span class="token operator">===</span> <span class="token punctuation">(</span>pattern<span class="token punctuation">[</span>matchIndex<span class="token punctuation">]</span> <span class="token operator">||</span> <span class="token string">''</span><span class="token punctuation">).</span><span class="token function">toLowerCase</span><span class="token punctuation">()</span>
              <span class="token operator">?</span> matchIndex <span class="token operator">+</span> <span class="token number">1</span>
              <span class="token punctuation">:</span> matchIndex<span class="token punctuation">,</span>
      <span class="token number">0</span>
  <span class="token punctuation">)</span> <span class="token operator">===</span> pattern<span class="token punctuation">.</span>length<span class="token punctuation">;</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">isSimilar</span><span class="token punctuation">(</span><span class="token string">'rt'</span><span class="token punctuation">,</span><span class="token string">'Rohit'</span><span class="token punctuation">);</span> <span class="token comment">// true</span>
<span class="token function">isSimilar</span><span class="token punctuation">(</span><span class="token string">'tr'</span><span class="token punctuation">,</span><span class="token string">'Rohit'</span><span class="token punctuation">);</span> <span class="token comment">// false</span>
</pre></div><div class="card code-card"><div class="section card-content"><h4 id="jsontodate.md">JSONToDate</h4><p>Converts a JSON object to a date.</p><p>Use <code>Date()</code>, to convert dates in JSON format to readable format (<code>dd/mm/yyyy</code>).</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">JSONToDate</span> <span class="token operator">=</span> arr <span class="token operator">=></span> <span class="token punctuation">{</span>
  <span class="token keyword">const</span> dt <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Date</span><span class="token punctuation">(</span><span class="token function">parseInt</span><span class="token punctuation">(</span>arr<span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">().</span><span class="token function">substr</span><span class="token punctuation">(</span><span class="token number">6</span><span class="token punctuation">)));</span>
  <span class="token keyword">return</span> <span class="token template-string"><span class="token string">`</span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">${</span>dt<span class="token punctuation">.</span><span class="token function">getDate</span><span class="token punctuation">()</span><span class="token interpolation-punctuation punctuation">}</span></span><span class="token string">/</span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">${</span>dt<span class="token punctuation">.</span><span class="token function">getMonth</span><span class="token punctuation">()</span> <span class="token operator">+</span> <span class="token number">1</span><span class="token interpolation-punctuation punctuation">}</span></span><span class="token string">/</span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">${</span>dt<span class="token punctuation">.</span><span class="token function">getFullYear</span><span class="token punctuation">()</span><span class="token interpolation-punctuation punctuation">}</span></span><span class="token string">`</span></span><span class="token punctuation">;
};</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">JSONToDate</span><span class="token punctuation">(</span><span class="token regex">/Date(1489525200000)/</span><span class="token punctuation">);</span> <span class="token comment">// "14/3/2017"</span>
</pre></div><div class="card code-card"><div class="section card-content"><h4 id="levenshteindistance.md">levenshteinDistance</h4><p>Calculates the <a href="https://en.wikipedia.org/wiki/Levenshtein_distance">Levenshtein distance</a> between two strings.</p><p>Calculates the number of changes (substitutions, deletions or additions) required to convert <code>string1</code> to <code>string2</code>. Can also be used to compare two strings as shown in the second example.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">levenshteinDistance</span> <span class="token operator">=</span> <span class="token punctuation">(</span>string1<span class="token punctuation">,</span> string2<span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span>string1<span class="token punctuation">.</span>length <span class="token operator">===</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token keyword">return</span> string2<span class="token punctuation">.</span>length<span class="token punctuation">;</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span>string2<span class="token punctuation">.</span>length <span class="token operator">===</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token keyword">return</span> string1<span class="token punctuation">.</span>length<span class="token punctuation">;</span>
  <span class="token keyword">let</span> matrix <span class="token operator">=</span> <span class="token function">Array</span><span class="token punctuation">(</span>string2<span class="token punctuation">.</span>length <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">)
    .</span><span class="token function">fill</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)
    .</span><span class="token function">map</span><span class="token punctuation">((</span>x<span class="token punctuation">,</span> i<span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">[</span>i<span class="token punctuation">]);</span>
  matrix<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token function">Array</span><span class="token punctuation">(</span>string1<span class="token punctuation">.</span>length <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">)
    .</span><span class="token function">fill</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)
    .</span><span class="token function">map</span><span class="token punctuation">((</span>x<span class="token punctuation">,</span> i<span class="token punctuation">)</span> <span class="token operator">=></span> i<span class="token punctuation">);</span>
  <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">let</span> i <span class="token operator">=</span> <span class="token number">1</span><span class="token punctuation">;</span> i <span class="token operator">&lt;=</span> string2<span class="token punctuation">.</span>length<span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">) {</span>
    <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">let</span> j <span class="token operator">=</span> <span class="token number">1</span><span class="token punctuation">;</span> j <span class="token operator">&lt;=</span> string1<span class="token punctuation">.</span>length<span class="token punctuation">;</span> j<span class="token operator">++</span><span class="token punctuation">) {</span>
      <span class="token keyword">if</span> <span class="token punctuation">(</span>string2<span class="token punctuation">[</span>i <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">]</span> <span class="token operator">===</span> string1<span class="token punctuation">[</span>j <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">]) {</span>
        matrix<span class="token punctuation">[</span>i<span class="token punctuation">][</span>j<span class="token punctuation">]</span> <span class="token operator">=</span> matrix<span class="token punctuation">[</span>i <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">][</span>j <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">];
      }</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
        matrix<span class="token punctuation">[</span>i<span class="token punctuation">][</span>j<span class="token punctuation">]</span> <span class="token operator">=</span> Math<span class="token punctuation">.</span><span class="token function">min</span><span class="token punctuation">(</span>
          matrix<span class="token punctuation">[</span>i <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">][</span>j <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">]</span> <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">,</span>
          matrix<span class="token punctuation">[</span>i<span class="token punctuation">][</span>j <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">]</span> <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">,</span>
          matrix<span class="token punctuation">[</span>i <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">][</span>j<span class="token punctuation">]</span> <span class="token operator">+</span> <span class="token number">1</span>
        <span class="token punctuation">);
      }
    }
  }</span>
  <span class="token keyword">return</span> matrix<span class="token punctuation">[</span>string2<span class="token punctuation">.</span>length<span class="token punctuation">][</span>string1<span class="token punctuation">.</span>length<span class="token punctuation">];
};</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">levenshteinDistance</span><span class="token punctuation">(</span><span class="token string">'30-seconds-of-code'</span><span class="token punctuation">,</span><span class="token string">'30-seconds-of-python-code'</span><span class="token punctuation">);</span> <span class="token comment">// 7</span>
<span class="token keyword">const</span> <span class="token function-variable function">compareStrings</span> <span class="token operator">=</span> <span class="token punctuation">(</span>string1<span class="token punctuation">,</span>string2<span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">(</span><span class="token number">100</span> <span class="token operator">-</span> <span class="token function">levenshteinDistance</span><span class="token punctuation">(</span>string1<span class="token punctuation">,</span>string2<span class="token punctuation">)</span> <span class="token operator">/</span> Math<span class="token punctuation">.</span><span class="token function">max</span><span class="token punctuation">(</span>string1<span class="token punctuation">.</span>length<span class="token punctuation">,</span>string2<span class="token punctuation">.</span>length<span class="token punctuation">));</span>
<span class="token function">compareStrings</span><span class="token punctuation">(</span><span class="token string">'30-seconds-of-code'</span><span class="token punctuation">,</span> <span class="token string">'30-seconds-of-python-code'</span><span class="token punctuation">);</span> <span class="token comment">// 99.72 (%)</span>
</pre></div><div class="card code-card"><div class="section card-content"><h4 id="pipelog.md">pipeLog</h4><p>Logs a value and returns it.</p><p>Use <code>console.log</code> to log the supplied value, combined with the <code>||</code> operator to return it.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">pipeLog</span> <span class="token operator">=</span> data <span class="token operator">=></span> console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>data<span class="token punctuation">)</span> <span class="token operator">||</span> data<span class="token punctuation">;</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">pipeLog</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">);</span> <span class="token comment">// logs `1` and returns `1`</span>
</pre></div><div class="card code-card"><div class="section card-content"><h4 id="quicksort.md">quickSort</h4><p>QuickSort an Array (ascending sort by default).</p><p>Use recursion. Use <code>Array.prototype.filter</code> and spread operator (<code>...</code>) to create an array that all elements with values less than the pivot come before the pivot, and all elements with values greater than the pivot come after it. If the parameter <code>desc</code> is truthy, return array sorts in descending order.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">quickSort</span> <span class="token operator">=</span> <span class="token punctuation">([</span>n<span class="token punctuation">,</span> <span class="token operator">...</span>nums<span class="token punctuation">],</span> desc<span class="token punctuation">)</span> <span class="token operator">=></span>
  <span class="token function">isNaN</span><span class="token punctuation">(</span>n<span class="token punctuation">)</span>
    <span class="token operator">?</span> <span class="token punctuation">[]
    : [</span>
        <span class="token operator">...</span><span class="token function">quickSort</span><span class="token punctuation">(</span>nums<span class="token punctuation">.</span><span class="token function">filter</span><span class="token punctuation">(</span>v <span class="token operator">=></span> <span class="token punctuation">(</span>desc <span class="token operator">?</span> v <span class="token operator">></span> n <span class="token punctuation">:</span> v <span class="token operator">&lt;=</span> n<span class="token punctuation">)),</span> desc<span class="token punctuation">),</span>
        n<span class="token punctuation">,</span>
        <span class="token operator">...</span><span class="token function">quickSort</span><span class="token punctuation">(</span>nums<span class="token punctuation">.</span><span class="token function">filter</span><span class="token punctuation">(</span>v <span class="token operator">=></span> <span class="token punctuation">(</span><span class="token operator">!</span>desc <span class="token operator">?</span> v <span class="token operator">></span> n <span class="token punctuation">:</span> v <span class="token operator">&lt;=</span> n<span class="token punctuation">)),</span> desc<span class="token punctuation">)
      ];</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">quickSort</span><span class="token punctuation">([</span><span class="token number">4</span><span class="token punctuation">,</span> <span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">]);</span> <span class="token comment">// [1,2,3,4]</span>
<span class="token function">quickSort</span><span class="token punctuation">([</span><span class="token number">4</span><span class="token punctuation">,</span> <span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">],</span> <span class="token boolean">true</span><span class="token punctuation">);</span> <span class="token comment">// [4,3,2,1]</span>
</pre></div><div class="card code-card"><div class="section card-content"><h4 id="removevowels.md">removeVowels</h4><p>Returns all the vowels in a <code>str</code> replaced by <code>repl</code>.</p><p>Use <code>String.prototype.replace()</code> with a regexp to replace all vowels in <code>str</code>. Omot <code>repl</code> to use a default value of <code>''</code>.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> removeVowels <span class="token operator">=</span> <span class="token punctuation">(</span>str<span class="token punctuation">,</span> repl <span class="token operator">=</span> <span class="token string">''</span><span class="token punctuation">)</span> <span class="token operator">=></span> str<span class="token punctuation">.</span><span class="token function">replace</span><span class="token punctuation">(</span><span class="token regex">/[aeiou]/gi</span><span class="token punctuation">,</span> repl<span class="token punctuation">);</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">removeVowels</span><span class="token punctuation">(</span><span class="token string">"foobAr"</span><span class="token punctuation">);</span> <span class="token comment">// "fbr"</span>
<span class="token function">removeVowels</span><span class="token punctuation">(</span><span class="token string">"foobAr"</span><span class="token punctuation">,</span><span class="token string">"*"</span><span class="token punctuation">);</span> <span class="token comment">// "f**b*r"</span>
</pre></div><div class="card code-card"><div class="section card-content"><h4 id="solverpn.md">solveRPN</h4><p>Solves the given mathematical expression in <a href="https://en.wikipedia.org/wiki/Reverse_Polish_notation">reverse polish notation</a>. Throws appropriate errors if there are unrecognized symbols or the expression is wrong. The valid operators are :- <code>+</code>,<code>-</code>,<code>*</code>,<code>/</code>,<code>^</code>,<code>**</code> (<code>^</code>&amp;<code>**</code> are the exponential symbols and are same). This snippet does not supports any unary operators.</p><p>Use a dictionary, <code>OPERATORS</code> to specify each operator's matching mathematical operation. Use <code>String.prototype.replace()</code> with a regular expression to replace <code>^</code> with <code>**</code>, <code>String.prototype.split()</code> to tokenize the string and <code>Array.prototype.filter()</code> to remove empty tokens. Use <code>Array.prototype.forEach()</code> to parse each <code>symbol</code>, evaluate it as a numeric value or operator and solve the mathematical expression. Numeric values are converted to floating point numbers and pushed to a <code>stack</code>, while operators are evaluated using the <code>OPERATORS</code> dictionary and pop elements from the <code>stack</code> to apply operations.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">solveRPN</span> <span class="token operator">=</span> rpn <span class="token operator">=></span> <span class="token punctuation">{</span>
  <span class="token keyword">const</span> <span class="token constant">OPERATORS</span> <span class="token operator">=</span> <span class="token punctuation">{</span>
    <span class="token string">'*'</span><span class="token punctuation">: (</span>a<span class="token punctuation">,</span> b<span class="token punctuation">)</span> <span class="token operator">=></span> a <span class="token operator">*</span> b<span class="token punctuation">,</span>
    <span class="token string">'+'</span><span class="token punctuation">: (</span>a<span class="token punctuation">,</span> b<span class="token punctuation">)</span> <span class="token operator">=></span> a <span class="token operator">+</span> b<span class="token punctuation">,</span>
    <span class="token string">'-'</span><span class="token punctuation">: (</span>a<span class="token punctuation">,</span> b<span class="token punctuation">)</span> <span class="token operator">=></span> a <span class="token operator">-</span> b<span class="token punctuation">,</span>
    <span class="token string">'/'</span><span class="token punctuation">: (</span>a<span class="token punctuation">,</span> b<span class="token punctuation">)</span> <span class="token operator">=></span> a <span class="token operator">/</span> b<span class="token punctuation">,</span>
    <span class="token string">'**'</span><span class="token punctuation">: (</span>a<span class="token punctuation">,</span> b<span class="token punctuation">)</span> <span class="token operator">=></span> a <span class="token operator">**</span> b
  <span class="token punctuation">};</span>
  <span class="token keyword">const</span> <span class="token punctuation">[</span>stack<span class="token punctuation">,</span> solve<span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token punctuation">[
    [],</span>
    rpn
      <span class="token punctuation">.</span><span class="token function">replace</span><span class="token punctuation">(</span><span class="token regex">/\^/g</span><span class="token punctuation">,</span> <span class="token string">'**'</span><span class="token punctuation">)
      .</span><span class="token function">split</span><span class="token punctuation">(</span><span class="token regex">/\s+/g</span><span class="token punctuation">)
      .</span><span class="token function">filter</span><span class="token punctuation">(</span>el <span class="token operator">=> !</span><span class="token regex">/\s+/</span><span class="token punctuation">.</span><span class="token function">test</span><span class="token punctuation">(</span>el<span class="token punctuation">)</span> <span class="token operator">&amp;&amp;</span> el <span class="token operator">!==</span> <span class="token string">''</span><span class="token punctuation">)
  ];</span>
  solve<span class="token punctuation">.</span><span class="token function">forEach</span><span class="token punctuation">(</span>symbol <span class="token operator">=></span> <span class="token punctuation">{</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span><span class="token function">isNaN</span><span class="token punctuation">(</span><span class="token function">parseFloat</span><span class="token punctuation">(</span>symbol<span class="token punctuation">))</span> <span class="token operator">&amp;&amp;</span> <span class="token function">isFinite</span><span class="token punctuation">(</span>symbol<span class="token punctuation">)) {</span>
      stack<span class="token punctuation">.</span><span class="token function">push</span><span class="token punctuation">(</span>symbol<span class="token punctuation">);
    }</span> <span class="token keyword">else if</span> <span class="token punctuation">(</span>Object<span class="token punctuation">.</span><span class="token function">keys</span><span class="token punctuation">(</span><span class="token constant">OPERATORS</span><span class="token punctuation">).</span><span class="token function">includes</span><span class="token punctuation">(</span>symbol<span class="token punctuation">)) {</span>
      <span class="token keyword">const</span> <span class="token punctuation">[</span>a<span class="token punctuation">,</span> b<span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token punctuation">[</span>stack<span class="token punctuation">.</span><span class="token function">pop</span><span class="token punctuation">(),</span> stack<span class="token punctuation">.</span><span class="token function">pop</span><span class="token punctuation">()];</span>
      stack<span class="token punctuation">.</span><span class="token function">push</span><span class="token punctuation">(</span><span class="token constant">OPERATORS</span><span class="token punctuation">[</span>symbol<span class="token punctuation">](</span><span class="token function">parseFloat</span><span class="token punctuation">(</span>b<span class="token punctuation">),</span> <span class="token function">parseFloat</span><span class="token punctuation">(</span>a<span class="token punctuation">)));
    }</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
      <span class="token keyword">throw</span> <span class="token template-string"><span class="token string">`</span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">${</span>symbol<span class="token interpolation-punctuation punctuation">}</span></span><span class="token string"> is not a recognized symbol`</span></span><span class="token punctuation">;
    }
  });</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span>stack<span class="token punctuation">.</span>length <span class="token operator">===</span> <span class="token number">1</span><span class="token punctuation">)</span> <span class="token keyword">return</span> stack<span class="token punctuation">.</span><span class="token function">pop</span><span class="token punctuation">();</span>
  <span class="token keyword">else throw</span> <span class="token template-string"><span class="token string">`</span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">${</span>rpn<span class="token interpolation-punctuation punctuation">}</span></span><span class="token string"> is not a proper RPN. Please check it and try again`</span></span><span class="token punctuation">;
};</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">solveRPN</span><span class="token punctuation">(</span><span class="token string">'15 7 1 1 + - / 3 * 2 1 1 + + -'</span><span class="token punctuation">);</span> <span class="token comment">// 5</span>
<span class="token function">solveRPN</span><span class="token punctuation">(</span><span class="token string">'2 3 ^'</span><span class="token punctuation">);</span> <span class="token comment">// 8</span>
</pre></div><div class="card code-card"><div class="section card-content"><h4 id="speechsynthesis.md">speechSynthesis</h4><p>Performs speech synthesis (experimental).</p><p>Use <code>SpeechSynthesisUtterance.voice</code> and <code>window.speechSynthesis.getVoices()</code> to convert a message to speech. Use <code>window.speechSynthesis.speak()</code> to play the message.</p><p>Learn more about the <a href="https://developer.mozilla.org/en-US/docs/Web/API/SpeechSynthesisUtterance">SpeechSynthesisUtterance interface of the Web Speech API</a>.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">speechSynthesis</span> <span class="token operator">=</span> message <span class="token operator">=></span> <span class="token punctuation">{</span>
  <span class="token keyword">const</span> msg <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">SpeechSynthesisUtterance</span><span class="token punctuation">(</span>message<span class="token punctuation">);</span>
  msg<span class="token punctuation">.</span>voice <span class="token operator">=</span> window<span class="token punctuation">.</span>speechSynthesis<span class="token punctuation">.</span><span class="token function">getVoices</span><span class="token punctuation">()[</span><span class="token number">0</span><span class="token punctuation">];</span>
  window<span class="token punctuation">.</span>speechSynthesis<span class="token punctuation">.</span><span class="token function">speak</span><span class="token punctuation">(</span>msg<span class="token punctuation">);
};</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">speechSynthesis</span><span class="token punctuation">(</span><span class="token string">'Hello, World'</span><span class="token punctuation">);</span> <span class="token comment">// // plays the message</span>
</pre></div></main><footer class="col-full-width container"><div class="col-centered"><p style="display:inline-block"><strong>30 seconds of code</strong> is licensed under the <a href="https://github.com/30-seconds/30-seconds-of-code/blob/master/LICENSE">CC0-1.0</a> license.<br>Logos made by <a href="https://github.com/Chalarangelo">Angelos Chalaris</a> and ribbon made by <a href="https://github.com/tholman/github-corners">Tim Holman</a> are licensed under the <a href="https://opensource.org/licenses/MIT">MIT</a> license.<br>Sponsored by <img src="https://30secondsofcode.org/sponsors/DO_Logo_icon_blue.svg" style="vertical-align:sub;padding-right:2px;padding-left:2px" width="20px" height="20px" alt="DigitalOcean"><a href="https://www.digitalocean.com"><span style="color:#0080ff">DigitalOcean</span></a>.</p><br/><p style="display:inline-block"><a href="./about">About</a>&nbsp;&nbsp;&nbsp;&nbsp;<a href="./contributing">Contributing</a>&nbsp;&nbsp;&nbsp;&nbsp;<a href="./archive">Archive</a>&nbsp;&nbsp;&nbsp;&nbsp;<a href="./glossary">Glossary</a></p></div></footer><a class="scroll-to-top" href="#top"></a></div></body></html>